package com.longmao.formvalidate.handler;

import com.longmao.formvalidate.controller.BaseController;
import com.longmao.formvalidate.exception.RestError;
import com.longmao.formvalidate.exception.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
    
    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<RestError> handleRunTimeException(RuntimeException e) {
        logger.error("", e);
        RestError restError = new RestError();
        restError.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        restError.setMessage("系统错误");
        restError.setCode(500);
        ResponseEntity<RestError> response = new ResponseEntity<>(restError, HttpStatus.BAD_REQUEST);
        return response;
    }

    @ExceptionHandler({Exception.class})
    public ResponseEntity<RestError> handleException(Exception e) {
        logger.error("", e);
        RestError restError = new RestError();
        restError.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        restError.setMessage("系统错误");
        restError.setCode(500);
        ResponseEntity<RestError> response = new ResponseEntity<>(restError, HttpStatus.BAD_REQUEST);
        return response;
    }

    @ExceptionHandler({ValidationException.class})
    public ResponseEntity<RestError> handleValidationException(ValidationException e, HttpServletRequest request) {
        logger.error(request.getRequestURL().toString() + "={}", e.getMessage());
        RestError restError = new RestError();
        restError.setStatus(HttpStatus.BAD_REQUEST.value());
        restError.setCode(e.getCode() != 0 ? e.getCode() : 400);
        restError.setMessage(e.getMessage());
        ResponseEntity<RestError> response = new ResponseEntity<>(restError, HttpStatus.BAD_REQUEST);
        return response;
    }
}
